package com.tianchi.lexiang.background;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import com.tianchi.lexiang.R;
import com.tianchi.lexiang.background.util.HddDataBaseVersion;
import com.tianchi.lexiang.background.util.ReaderSongExcle;
import com.tianchi.lexiang.background.util.UDiskAddSongUtil;
import com.tianchi.lexiang.bean.LeXiangConstants;
import com.tianchi.lexiang.bean.Song;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class BatchAddSongs extends Activity implements OnClickListener {

	private static final String TAG = "BatchAddSongs";
	private static final String desPath = LeXiangConstants.SONG_HARD_DISK_PATH;
	private static final String srcPath = LeXiangConstants.BATCH_ADD_SONG_PATH;

	private TextView batchAddsongInfoTxt;

	private TextView songNameTxt;
	private TextView singerNameTxt;
	private TextView songNameSpellTxt;
	private TextView songNameWordsTxt;
	private TextView volumeTxt;
	private TextView songTypeTxt;
	private TextView languageTxt;
	private TextView originalTrackTxt;

	private TextView hardDiskInfoTxt;

	private Button previousBtn;
	private Button nextBtn;

	private ProgressBar copyProgressBar;
	private TextView copyProgressTxt;

	private Button startAddsongBtn;
	private Button pauseAddsongBtn;
	private Button backBtn;

	private List<Song> list = null;
	private ReaderSongExcle instance = null;

	private int totalNumbers = 0;
	private int currentNumber = 1;
	private int cureentAddSongNumber = 1;

	private String songsNumberInfo = "";

	private boolean bool = true;
	boolean checkBoxIsChecked = false;
	private String myChiose = "";

	private long residualSize;
	private long canAddSongNum;

	private static final String REPLACE = "repalce";
	private static final String New_INSCREAN = "newIncrease";
	private static final String NEXT_SONG = "nextSong";
	private static final String NULL = "null";

	private UDiskAddSongUtil uDiskAddSongUtil = null;

	private Song song;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (cureentAddSongNumber < totalNumbers) {
				showSongInfo(cureentAddSongNumber);
				song = list.get(cureentAddSongNumber - 1);
				int maxSongNum = uDiskAddSongUtil.getMaxSongNum() + 1;
				song.number = maxSongNum;
				if (uDiskAddSongUtil.retrievalSongInfo(song)) {
					if (myChiose != null && !"".equals(myChiose)) {
						if (NEXT_SONG.equals(myChiose)) {
							cureentAddSongNumber++;
							handler.sendEmptyMessage(0);
						} else {
							new InsertTask().execute(myChiose);
						}
					} else {
						isExistDialog();
					}
				} else {
					new InsertTask().execute(NULL);
				}
			} else {
				startAddsongBtn.setEnabled(true);
				backBtn.setEnabled(true);
				previousBtn.setEnabled(true);
				nextBtn.setEnabled(true);
				pauseAddsongBtn.setEnabled(false);
				HddDataBaseVersion.setCurrentHddDataBaseVersion();
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.batch_add_song);
		this.onNewIntent(getIntent());
		initView();
		if (instance == null) {
			instance = ReaderSongExcle.getInstance();
		}
		if (uDiskAddSongUtil == null) {
			uDiskAddSongUtil = UDiskAddSongUtil.getInstance(this);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		residualSize = intent.getLongExtra(NetworkAddSong.RESIDUAL_SIZE, 0);
		canAddSongNum = intent.getLongExtra(NetworkAddSong.CAN_ADD_SONG_NUM, 0);
	}

	private void initView() {
		batchAddsongInfoTxt = (TextView) findViewById(R.id.batch_addsong_info_txt);

		hardDiskInfoTxt = (TextView) findViewById(R.id.hard_disk_info_txt);
		
		hardDiskInfoTxt.setText(getString(R.string.residual_capacity)
				+ residualSize + getString(R.string.gb) + ";"
				+ getString(R.string.sava_song_num) + canAddSongNum
				+ getString(R.string.precise_addsong_info));

		songNameTxt = (TextView) findViewById(R.id.song_name_txt);

		singerNameTxt = (TextView) findViewById(R.id.singer_name_txt);

		songNameSpellTxt = (TextView) findViewById(R.id.song_name_spell_txt);

		songNameWordsTxt = (TextView) findViewById(R.id.song_name_words_txt);

		volumeTxt = (TextView) findViewById(R.id.volume_txt);

		songTypeTxt = (TextView) findViewById(R.id.song_type_txt);

		languageTxt = (TextView) findViewById(R.id.language_txt);

		originalTrackTxt = (TextView) findViewById(R.id.original_track_txt);

		copyProgressBar = (ProgressBar) findViewById(R.id.copy_progress_bar);
		copyProgressBar.setMax(100);

		copyProgressTxt = (TextView) findViewById(R.id.copy_progress_txt);

		startAddsongBtn = (Button) findViewById(R.id.start_addsong_btn);
		startAddsongBtn.setOnClickListener(this);

		pauseAddsongBtn = (Button) findViewById(R.id.pause_addsong_btn);
		pauseAddsongBtn.setOnClickListener(this);

		backBtn = (Button) findViewById(R.id.back_btn);
		backBtn.setOnClickListener(this);

		previousBtn = (Button) findViewById(R.id.previous);
		pauseAddsongBtn.setEnabled(false);
		previousBtn.setOnClickListener(this);

		nextBtn = (Button) findViewById(R.id.next);
		nextBtn.setOnClickListener(this);

	}

	@Override
	protected void onStart() {
		super.onStart();
		list = instance.getAllSongsInfo(LeXiangConstants.EXCLE_PATH);
		totalNumbers = list.size();
		songsNumberInfo = getString(R.string.batch_add_songs_number_info)
				+ totalNumbers + getString(R.string.initial);

	}

	@Override
	protected void onResume() {
		super.onResume();
		batchAddsongInfoTxt.setText(songsNumberInfo);
		showSongInfo(currentNumber);
	}

	private void showSongInfo(int number) {
		if(number > 0){
			Song mSong = list.get(number - 1);
			songNameTxt.setText(mSong.songName);
			singerNameTxt.setText(mSong.singerName);
			songNameSpellTxt.setText(mSong.firstSpell);
			songNameWordsTxt.setText(mSong.nameLength + "");
			volumeTxt.setText(mSong.leftArea + "");
			songTypeTxt.setText(mSong.type);
			languageTxt.setText(mSong.language);
			originalTrackTxt.setText(mSong.mtvOrVcd);
		}

	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch (id) {
		case R.id.start_addsong_btn:
			bool = true;
			startAddsongBtn.setEnabled(false);
			backBtn.setEnabled(false);
			previousBtn.setEnabled(false);
			nextBtn.setEnabled(false);
			pauseAddsongBtn.setEnabled(true);
			handler.sendEmptyMessage(0);
			break;
		case R.id.pause_addsong_btn:
			startAddsongBtn.setEnabled(true);
			backBtn.setEnabled(true);
			previousBtn.setEnabled(true);
			nextBtn.setEnabled(true);
			pauseAddsongBtn.setEnabled(false);
			bool = false;
			break;

		case R.id.back_btn:
			BatchAddSongs.this.finish();
			break;
		case R.id.previous:
			showPrevious();
			break;
		case R.id.next:
			showNext();
			break;

		default:
			break;
		}

	}

	private void showPrevious() {
		if (currentNumber > 1) {
			currentNumber--;
			showSongInfo(currentNumber);
		}
	}

	private void showNext() {
		if (currentNumber < totalNumbers) {
			currentNumber++;
			showSongInfo(currentNumber);
		}
	}

	protected void isExistDialog() {

		AlertDialog.Builder builder = new Builder(BatchAddSongs.this);
		builder.setIcon(android.R.drawable.ic_menu_help);
		builder.setTitle(getString(R.string.whether_to_replace));
		builder.setMultiChoiceItems(
				new String[] { getString(R.string.remember_my_choice) },
				new boolean[] { false },
				new DialogInterface.OnMultiChoiceClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which,
							boolean isChecked) {
						checkBoxIsChecked = isChecked;
					}
				});
		builder.setPositiveButton(getString(R.string.repalce),
				new Dialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (checkBoxIsChecked) {
							myChiose = REPLACE;
						}
						new InsertTask().execute(REPLACE);
						dialog.dismiss();
					}
				});

		builder.setNeutralButton(getString(R.string.new_increased),
				new Dialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (checkBoxIsChecked) {
							myChiose = New_INSCREAN;
						}
						new InsertTask().execute(New_INSCREAN);
						dialog.dismiss();
					}
				});

		builder.setNegativeButton(getString(R.string.next_singer),
				new Dialog.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (checkBoxIsChecked) {
							myChiose = NEXT_SONG;
						}
						cureentAddSongNumber++;
						handler.sendEmptyMessage(0);
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	class InsertTask extends AsyncTask<String, Integer, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			String des = desPath + song.number + "." + song.format;
			String songSourceName = song.singerName + "-" + song.songName;
			String src = srcPath + songSourceName + "." + song.format;
			if (REPLACE.equals(params[0])) {
				Log.d(TAG, "[doInBackground]......REPLACE");
				song.number = uDiskAddSongUtil.getSongNumber(song);
				des = desPath + song.number + "temp" + "." + song.format;
			}
			if (New_INSCREAN.equals(params[0])) {
				Log.d(TAG, "[doInBackground]......New_INSCREAN");
				song.songName = song.songName
						+ getString(R.string.new_song_add);
			}
			try {
				InputStream inputStream = new FileInputStream(src);
				float length = inputStream.available();
				OutputStream outputStream = new FileOutputStream(des);
				byte[] bytes = new byte[8 * 1024];
				int readLength = 0;
				long localLength = 0;
				while ((readLength = inputStream.read(bytes)) != -1) {
					Log.d(TAG, "[doInBackground]....readLength===>"
							+ readLength);
					localLength += readLength;
					Log.d(TAG, "[doInBackground]....localLength===>"
							+ localLength);
					publishProgress((int) ((localLength * 100) / length));
					outputStream.write(bytes, 0, readLength);
					outputStream.flush();
				}
				if (REPLACE.equals(params[0])) {
					Log.d(TAG, "doInBackground............rename");
					File file = new File(desPath, song.number + "temp" + "."
							+ song.format);
					file.renameTo(new File(desPath, song.number + "."
							+ song.format));
					des = desPath + song.number + "." + song.format;
				}
				Log.d(TAG, "[DownloadTask].....des===>" + des);
				Process p = Runtime.getRuntime().exec("chmod 777 " + des);
				if (p.waitFor() == 0) {
					Log.d(TAG, "[DownloadTask].....chmod success");
				} else {
					Log.d(TAG, "[DownloadTask].....chmod fialed");
				}
				inputStream.close();
				outputStream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return params[0];

		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
			copyProgressBar.setProgress(values[0]);
			copyProgressTxt.setText(values[0] + "%");
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (REPLACE.equals(result)) {
				uDiskAddSongUtil.updateSongInfo(song);
			} else {
				uDiskAddSongUtil.insertSongInfo(song);
			}
			cureentAddSongNumber++;
			if (bool) {
				handler.sendEmptyMessage(0);
			}
		}
	}

}
